﻿@using mscook.mvc;
<script>
    $(function () {
        @{  
                <text>
        var nameInput = "@ViewData["nameInput"]";
        var idInput = "@ViewData["idInput"]";
        var linkBtn = "@ViewData["linkBtn"]";

        (function () {
            var oldId = $("#" + idInput).val();
            $("a.btn-success").each(function () {
                var id = $(this).data("id");
                if (oldId.indexOf(id) >= 0) {
                    $(this).removeClass("btn-success").addClass("btn-danger").html("<i class='icon-trash icon-white'></i>Remove");
                }
            });
        })();

        $(".multi a.btn-success").live("click", function () {
            var name = $(this).data("name");
            var id = $(this).data("id");
            var oldName=$("#" + nameInput).val();
            var oldId=  $("#" + idInput).val();
            pushNew( $("#" + idInput),oldId,id);
            pushNew($("#" + nameInput), oldName, name);
            $(this).removeClass("btn-success").addClass("btn-danger").html("<i class='icon-trash icon-white'></i>Remove");
            return false;


        });

        $(".multi a.btn-danger").live("click", function () {
            var name = $(this).data("name");
            var id = $(this).data("id");
            var oldName = $("#" + nameInput).val();
            var oldId = $("#" + idInput).val();
            remove($("#" + idInput), oldId, id);
            remove($("#" + nameInput), oldName, name);
            $(this).removeClass("btn-danger").addClass("btn-success").html("<i class='icon-zoom-in icon-white'></i>Select");
            return false;
        });


        function pushNew(input,oldVal, newVal) {
            if(oldVal.indexOf(newVal)<0)
            {
                if (oldVal == "") {
                    input.val(newVal);
                }
                else {
                    input.val(oldVal + "," + newVal);
                }
            }

        };

        function remove(input,oldVal, newVal)
        {
            if(oldVal.indexOf(newVal)>=0)
            {
                oldVal=oldVal.replace(","+newVal ,"");
                oldVal=oldVal.replace(newVal, "");
                input.val(oldVal);
            }
        }

        </text>
        }

    });
</script>
